<template>
  <div>
    <customDialog
      :title="`${title}`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="650"
    >
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="90px"
        class="form_box"
        size="large"
      >
        <template v-if="title === '批量补单'">
          <el-row>
            <el-col :span="16">
              <p class="size_16">
                符合筛选条件的订单有
                <span class="blue">{{ form.selectNums }}</span> 条
              </p>
            </el-col>
          </el-row>
          <el-row style="margin: 10px 0">
            <el-col :span="16">
              <el-form-item label="补单数量" prop="topCount">
                <el-input-number
                  v-model="form.topCount"
                  :min="0"
                  :max="form.selectNums === 0 ? 0 : Infinity"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: -25px">
            <el-col :span="16">
              <el-form-item label="">
                <p class="grey size_14">优先对最新订单进行补单</p>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-row>
            <el-col :span="16">
              <p class="size_14">
                请输入转化金额，所填写金额会根据回传配置打折：
              </p>
            </el-col>
          </el-row>
          <el-row style="margin: 10px 0">
            <el-col :span="14">
              <el-form-item label="转化金额：" prop="amount">
                <el-input v-model.number="form.amount" size="default" />
              </el-form-item>
            </el-col>
            &nbsp;
            <el-col :span="4">
              <el-form-item label="单位：分" />
            </el-col>
          </el-row>
        </template>
      </el-form>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import customDialog from "@/components/CustomDialog/index.vue";
import type { FormInstance } from "element-plus";
import { cloneDeep } from "lodash-es";
import { orderBatch, registeredManual } from "@/api/echoRecord/index";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const form = ref({
  amount: undefined, // 转化金额
  topCount: 0, // 补单数量
  selectNums: 0, // 筛选数量
});
const formData = ref();
const registId = ref<number>(0);
const title = ref<string>("");

const validataAmount = (rule: any, value: any, callback: any) => {
  let reg = /^[0-9]\d*$/; // 大于0的整数
  if (!+value && value != 0) {
    return callback(new Error("转化金额只能输入整数"));
  } else if (!reg.test(value)) {
    return callback(new Error("转化金额只能输入整数"));
  } else {
    callback();
  }
};

const rules = reactive({
  topCount: [{ required: true, message: "补单数量不能为0", trigger: "blur" }],
  amount: [{ required: true, validator: validataAmount, trigger: "blur" }],
});

// 改变数量
const handleChange = () => {
  if (formData.value.selectNums <= 0) {
    formData.value.topCount = 0;
  }
};

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  if (title.value == "批量补单") {
    formData.value.topCount = 0;
  } else {
    form.value.amount = undefined;
  }
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL, params;
      // 批量补单
      if (title.value == "批量补单") {
        URL = orderBatch;
        params = formData.value;
        if (params.topCount <= 0) {
          return ElMessage.error("抱歉，符合条件的订单数需要大于0");
        }
      } else {
        // 注册流水转化
        URL = registeredManual;
        params = { id: registId.value, amount: form.value?.amount };
      }
      URL(params).then(() => {
        ElMessage.success(`${title.value}成功`);
        dialogVisible.value = false;
        closeDialog(ruleFormRef.value);
        emit("success");
      });
    }
  });
};

// 父级电子显示dialog
const showDialog = (val: any, str: string) => {
  // console.log("显示补单参数", val, str);
  dialogVisible.value = true;
  if (str == "补单") {
    title.value = "批量补单";
    val.topCount = 0;
    formData.value = cloneDeep(val);
    form.value = formData.value;
  } else {
    title.value = `对用户（${val?.id}）进行手动优化`;
    registId.value = val.id;
  }
};

defineExpose({
  showDialog,
});
</script>
<style scoped lang="scss"></style>
